#ifndef EDITFORMWRAPPER_H
#define EDITFORMWRAPPER_H



#include "AbstractEditFormActions.h"



#include <ItemModel.h>
#include <FileHandler.h>
//#include <D20BaseModel.h>


#include <QWidget>
#include <QFileDialog>
#include <QMessageBox>
#include <QTimer>
#include <QDebug>
#include <QAction>



// todo: content of this code could be moved to BaseEditForm.
template<typename EDITFORM>
class EditFormWrapper : public EDITFORM
{
public:

    EditFormWrapper(QWidget* parent = 0)
        : EDITFORM(parent)
    {
        m_actions = 0;
    }

    virtual RootItem* root() const
    {
        return m_root.data();
    }


    virtual void open(RootItem* root)
    {
        m_root = root;

        initialize();
        setupActions();
    }


    bool save()
    {
        if (!root()) return true;

        // update all appropriate data from this form
        updateData();

        QString file_path = root()->filePath();
        if (file_path.isEmpty() || !QFile::exists(file_path))
        {
            return saveAs();
        }

        return FileHandler::save(root(), file_path);
    }


    bool saveAs()
    {
        if (!root()) return true;

        QString file_path = QFileDialog::getSaveFileName(this, tr("Save File"), QDir::currentPath(), tr("Xml File (*.xml)"));
        if (file_path.isEmpty()) return true;

        return FileHandler::save(root(), file_path);
    }


    bool changed() const
    {
        if (!root()) return false;

        return root()->isDirty();
    }



protected:

    virtual void setupActions()
    {
        if (m_actions || !model()) return;

        m_actions = new QActionGroup(this);
        m_actions->setObjectName("modelActions");

        //qDebug() << Q_FUNC_INFO;
        foreach (int group, model()->groups())
        {
            QString name = model()->groupName(group);
            //qDebug() << name;

            QString text = QString("%1 %2").arg(QObject::tr("Add")).arg(name);
            QAction* action = new QAction(text, m_actions);
            //action->setObjectName(QString("action%1").arg(text.replace(" ","_")));
            action->setData(group);

            if (group > 9) continue;

            action->setShortcut(QKeySequence(QString("Ctrl+%1").arg(group + 1)));
            action->setToolTip(action->shortcut().toString());
        }

        addActions(m_actions->actions());

        connect(m_actions, SIGNAL(triggered(QAction*)), this, SLOT(onActionTriggered(QAction*)));
    }

    QPointer<RootItem> m_root;
    QActionGroup* m_actions;


};





#endif // EDITFORMWRAPPER_H


